using System;

namespace Voodoo.Sauce.LoadingTime
{
	internal class LoadingTimer
	{
		private DateTimeOffset _start;

		private DateTimeOffset? _end;

		private DateTimeOffset? _startPause;

		private long _pauseInMilliseconds;

		internal LoadingTimer()
		{
			_start = new DateTimeOffset(DateTime.UtcNow);
		}

		internal LoadingTimer(DateTimeOffset start)
		{
			_start = start;
		}

		internal void Pause()
		{
			if (IsStopped())
			{
				_startPause = null;
			}
			else if (!_startPause.HasValue)
			{
				_startPause = DateTimeOffset.Now;
			}
		}

		internal void Unpause()
		{
			if (IsStopped())
			{
				_startPause = null;
				return;
			}
			DateTimeOffset now = DateTimeOffset.Now;
			DateTimeOffset dateTimeOffset = _startPause ?? now;
			_pauseInMilliseconds += now.ToUnixTimeMilliseconds() - dateTimeOffset.ToUnixTimeMilliseconds();
			_startPause = null;
		}

		internal void SetEnd(DateTimeOffset end)
		{
			if (!IsStopped())
			{
				_end = end;
			}
		}

		internal long Stop()
		{
			SetEnd(DateTimeOffset.Now);
			return GetDuration();
		}

		internal bool IsStopped()
		{
			return _end.HasValue;
		}

		internal long GetStartTimestamp()
		{
			return _start.ToUnixTimeMilliseconds();
		}

		internal long GetEndTimestamp()
		{
			return _end?.ToUnixTimeMilliseconds() ?? 0;
		}

		internal long GetDuration()
		{
			if (!IsStopped())
			{
				return -1L;
			}
			return GetEndTimestamp() - GetStartTimestamp() - _pauseInMilliseconds;
		}
	}
}
